//index.js
const util = require('../../util/tools.js')
const app = getApp()
const db = wx.cloud.database()
const _ = db.command

Page({
  data: {
    formData: {},
    requestResult: '',
    roomId: '',
    trafficTypes: ['数学1', '数学2', '数学3'],
    trafficIndex: 0,
    radioItems: [{
        name: '数学1',
        value: 'airplane',
        checked: true
      },
      {
        name: '数学2',
        value: 'train'
      },
      {
        name: '其他',
        value: 'other'
      }
    ],
    introductionVisible: false
  },

  // 加载时执行
  onLoad: function() {
    if (!wx.cloud) {
      wx.redirectTo({
        url: '../chooseLib/chooseLib',
      })
      return
    }
    // wx.navigateTo({
    //   url: '../room/room?roomId=da51bd8c5e3e49f40c2d9444070f9b02',
    // })
    db.collection("report").where({}).get()

    var ddstr = util.getDateStr()
    this.setData({
      date: ddstr
    })
    this.setTypeValue("airplane")
  },

  // 日期变化处理
  bindDateChange: function(e) {
    this.setData({
      date: e.detail.value
    })
  },

  // 设置交通类型和placeholder
  setTypeValue(n) {
    switch (n) {
      case "airplane":
        this.setData({
          typeName: '加法',
          hitValue: '1+1'
        })
        break
      case "train":
        this.setData({
          typeName: '减法',
          hitValue: '如D3232 2号车厢'
        })
        break
      case "car":
        this.setData({
          typeName: '乘法',
          hitValue: '如天河客运站广州-深圳'
        })
        break
      case "other":
        this.setData({
          typeName: '除法',
          hitValue: '如江村到新村的三轮车'
        })
        break
    }
  },

  // 提交表单
  formSubmit: function(e) {
    var vals = e.detail.value
    this.setData({
      formData: vals,
    })
  },

  // 生成二维码
  onGetWXACode(e) {
    if (this.getwxaCode(e)) {
      wx.hideLoading()
    }
  },

  // 查询是否有确诊同行班次
  checkTraffic(e) {
    if (this.data.formData.typeValue == "") {
      wx.showToast({
        title: this.data.typeName + '不能为空',
        icon: 'none',
        duration: 2000
      })
      return
    }
    const self = this
    // 从上报查询
    db.collection('roomInfo').where({
      typeName: this.data.formData.typeName,
      typeValue: this.data.formData.typeValue,
      date: this.data.formData.date
    }).get({
      success: res => {
        if (res.errMsg === 'collection.get:ok' && res.data.length > 0) {
          const flight = res.data[0]
          db.collection('report').where({
            roomId: flight._id,
            review: 1 // 只查审核过的病例
          }).get({
            success: res => {
              if (res.errMsg === 'collection.get:ok' && res.data.length > 0) {
                wx.showModal({
                  title: '查询结果',
                  content: self.data.typeName + self.data.formData.typeValue + '存在新冠病例，请注意安全，及时隔离！',
                  showCancel: false
                })
              } else {
                this.checkFromOpenSource()
              }
            },
            fail: console.error
          })
        } else {
          this.checkFromOpenSource()
        }
      },
      fail: console.error
    })
  },

  checkFromOpenSource() {
    const self = this
    // 从公开数据源查询
    let key = ''
    switch (this.data.formData.typeName) {
      case "airplane":
        key = '飞机'
        break
      case "train":
        key = '火车'
        break
      case "car":
        key = _.in(['出租车', '公交车'])
        break
      default:
        break
    }
    let date = util.translateDate(this.data.formData.date)
    db.collection('traffic').where({
      t_type: key,
      t_no: this.data.formData.typeValue,
      t_date: date
    }).get({
      success: res => {
        if (res.errMsg === 'collection.get:ok' && res.data.length > 0) {
          wx.showModal({
            title: '查询结果',
            content: self.data.typeName + self.data.formData.typeValue + '存在新冠病例，请注意安全，及时隔离！',
            showCancel: false
          })
        } else {
          // 安全
          wx.showModal({
            title: '查询结果',
            content: '恭喜你！' + self.data.typeName + self.data.formData.typeValue + '安全，请关注后续信息',
            showCancel: false
          })
        }
      },
      fail: console.error
    })
  },

  // 订阅处理
  onGetUserInfo(e) {
    if (!e.detail.userInfo) {
      wx.showToast({
        title: '请允许获取信息',
        icon: 'none',
      })
      return
    }
    this.setData({
      userInfo: e.detail.userInfo
    })
    var vals = this.data.formData
    console.log('submit', vals)
    if (vals.typeValue == "") {
      wx.showToast({
        title: this.data.typeName + '不能为空',
        icon: 'none',
        duration: 2000
      })
      return
    }
    wx.showLoading({
      title: '正在生成',
    })
    var roomInfo = {
      key: vals.typeName + '-' + vals.typeValue + '-' + vals.date,
      typeName: vals.typeName,
      typeValue: vals.typeValue,
      date: vals.date
    }
    var self = this
    db.collection("roomInfo").add({
      data: roomInfo,
      success: function(e) {
        console.log("add room succ", e._id)
        roomInfo.id = e._id
        self.onGetWXACode(roomInfo)
      },
      fail: function(e) {
        db.collection("roomInfo").where({
          key: roomInfo.key
        }).get({
          success: function(e) {
            console.log("get room succ", e)
            roomInfo.wxacode = e.data[0].wxacode
            roomInfo.id = e.data[0]._id
            self.onGetWXACode(roomInfo)
          },
          fail: function(e) {
            wx.showToast({
              title: '内部错误, 请稍后重试',
            })
            wx.hideLoading()
          }
        })
      }
    })
  },

  // 加入同行
  joinRoom: function() {
    var roomId = this.data.roomId
    var openId = app.globalData.openid
    var userInfo = this.data.userInfo
    if (!userInfo)
      var self = this
    if (!openId) {
      setTimeout(function() {
        self.joinRoom(roomId, userInfo)
      }, 2000)
      return
    }
    db.collection("member").doc(roomId + '_' + openId).set({
      data: {
        openId: openId,
        roomId: roomId,
        status: 0,
        src: userInfo.avatarUrl,
        userInfo: userInfo,
      },
      success: function(e) {
        console.log("join succ", e)
      },
      fail: console.log
    })
  },

  // 获取同行二维码
  getwxaCode(e) {
    var roomId = e.id
    if (!roomId) {
      console.log("empty room id")
      return true
    }

    if (e.wxacode) {
      console.log("use cache wxacode", e.wxacode)
      this.setData({
        roomId: roomId,
        wxacodeSrc: e.wxacode,
        wxacodeResult: 'succ',
      })
      this.joinRoom()
      return true
    }

    console.log("start get code", roomId)

    this.setData({
      roomId: roomId,
      wxacodeSrc: '',
      wxacodeResult: '',
    })

    var self = this
    // 此处为演示，将使用 localStorage 缓存，正常开发中文件 ID 应存在数据库中
    const fileID = wx.getStorageSync('wxacodeCloudID_' + roomId)

    if (fileID) {
      // 有云文件 ID 缓存，直接使用该 ID
      // 如需清除缓存，选择菜单栏中的 “工具 -> 清除缓存 -> 清除数据缓存”，或在 Storage 面板中删掉相应的 key
      this.setData({
        roomId: roomId,
        wxacodeSrc: fileID,
        wxacodeResult: `从本地缓存中取得了小程序码的云文件 ID`,
      })
      console.log(`从本地缓存中取得了小程序码的云文件 ID：${fileID}`)
      self.joinRoom()
      return true
    }

    wx.cloud.callFunction({
      name: 'openapi',
      data: {
        action: 'getWXACode',
        path: '/pages/room/room?roomId=' + roomId
      },
      success: res => {
        console.warn('[云函数] [openapi] wxacode.get 调用成功：', res)
        db.collection('roomInfo').doc(roomId).update({
          data: {
            'wxacode': res.result
          },
          success: function() {
            self.setData({
              roomId: roomId,
              wxacodeSrc: res.result,
              wxacodeResult: `云函数获取二维码成功`,
            })
            wx.setStorageSync('wxacodeCloudID_' + roomId, res.result)
            wx.hideLoading()
            self.joinRoom()
          },
          fail: function(e) {
            wx.hideLoading()
          },
        })
      },
      fail: err => {
        wx.hideLoading()
        wx.showToast({
          icon: 'none',
          title: '调用失败',
        })
        console.error('[云函数] [openapi] wxacode.get 调用失败：', err)
      }
    })

    return false
  },

  // 交通类型变化处理
  bindTypeChange: function(e) {
    const typeValue = this.data.radioItems[e.detail.value].value
    this.setTypeValue(typeValue)
    let radioItems = this.data.radioItems;
    for (var i = 0, len = radioItems.length; i < len; ++i) {
      radioItems[i].checked = radioItems[i].value == typeValue;
    }
    this.setData({
      trafficIndex: e.detail.value,
      radioItems: radioItems
    });
  },

  // 显示查看说明
  showIntroduction: function(e) {
    this.setData({
      introductionVisible: true
    })
  },

  // 关闭查看说明
  closeIntroduction: function(e) {
    this.setData({
      introductionVisible: false
    })
  },

  // 分享
  onShareAppMessage: function() {

  }
})